import sys
import os
import copy
from jinja2 import Environment, PackageLoader, Template, FileSystemLoader
import mdf.debug
import mdf.config

loader = FileSystemLoader( mdf.config.default_template_dir )
env = Environment( loader = loader )

class IndexFile():
	def __init__( self, filename ):
		self.filename = filename
		mdf.debug.dprint( filename )

	def render( self, packages ):
		#select last 10 posts
		last10 = []
		for pkg in packages:
			last10.append( pkg.writeup )
		last10 = sorted( last10, key = lambda article: article.date_extended )
		last10 = copy.deepcopy( last10[len(last10)-10:] )
		#last5 = reversed( last5 )
		last10.reverse()
		#for i in range(0,len(last10)):
		#	last10[i].article = last10[i].article[:100]
		
		#generate template
		templ = env.get_template("index.thtml")
		f = open( self.filename, "w" )
		f.write( templ.render( posts=last10 ) )
		f.close()
		
		del last10
